<template>
  <div>
    {{ formattedTime }}
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
// 定义当前时间的状态
const formattedTime = ref('');

// 更新时间的方法
const updateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，所以加1
  const day = now.getDate().toString().padStart(2, '0');
  const hours = now.getHours().toString().padStart(2, '0');
  const minutes = now.getMinutes().toString().padStart(2, '0');
  const seconds = now.getSeconds().toString().padStart(2, '0');

  // 获取星期几
  const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  const dayOfWeek = weekDays[now.getDay()];

  formattedTime.value = `${year}-${month}-${day}  ${hours}:${minutes}:${seconds} ${dayOfWeek}`;
};

//实时时间
// 在组件挂载后开始定时更新时间
let timer = null;
onMounted(() => {
  updateTime(); // 首次加载时立即更新时间
  timer = setInterval(updateTime, 1000);

});

// 在组件卸载前清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});

</script>

<style lang='scss' scoped>

</style>
